var aFunc = {

	backMethod: function() {
		var old_back = mui.back;
		mui.back = function(event) {
			var opener = plus.webview.currentWebview().opener();
			mui.fire(opener, 'reloadHome');
			old_back();
			return false;
		};
	},
	plusReady: function() {
		if (mui.os.plus) {
			plus.navigator.closeSplashscreen();
			plus.screen.lockOrientation("portrait-primary");
			plus.navigator.setStatusBarBackground(common.colour.statusBackground);
			aVariable.webview.current = plus.webview.currentWebview();
			// aVariable.webview.current.setStyle({
			// 	bounce: "vertical",
			// 	bounceBackground: common.colour.pageBackground,
			// });
		}

		aVariable.webview.current.setStyle({
			bounce: "vertical",
			bounceBackground: common.colour.pageBackground,
		});
		aFunc.bindEvent();
		aFunc.backMethod();
		aFunc.loadToday();

		window.addEventListener('reloadView', function(event) {
			aFunc.getCalendarData(aVariable.data.lastDateStr);
			aFunc.requestUserDaySign(aVariable.data.lastDateStr, "noshow");
		});
		window.addEventListener('selectMonth', function(event) {
			var year = event.detail.year;
			var month = event.detail.month;
			var day = event.detail.day;

			//顶部日期信息
			var lunarData = lunarTool.sloarToLunar(year, month, day)
			var lunarDay = lunarData.lunarDay;
			aFunc.dateTopView(year, month, day, lunarDay);
			//创建日历以及当月打卡信息
			aFunc.creatCalendar(parseInt(year), parseInt(month - 1));
			var dateStr = year + "-" + month + "-" + day;
			aVariable.data.lastDateStr = dateStr;
			aFunc.getCalendarData(dateStr);
			//隐藏底部打卡信息
			aVariable.view.shiftInfo.style.display = "none";
		});


	},

	//获取日历信息
	getCalendarData: function(dateStr) {
		attendServer.attcalendar(dateStr, function(data) {
			if (data.code == "200") {
				if (data.data.length > 0) {
					for (var i = 0; i < data.data.length; i++) {
						var daydata = data.data[i];
						var todayID = "days" + daydata.day;
						var todayholiID = "holi" + daydata.day;
						var day = document.getElementById(todayID);
						var dayholi = document.getElementById(todayholiID);
						if (daydata.isWorkDay == 1) {
							//是工作日
							var result = day.getElementsByClassName("two")[0];
							var point = day.getElementsByClassName("point")[0];
							result.innerHTML = daydata.resultName.length > 0 ? daydata.resultName :
								"&nbsp";
							var attResult = daydata.attResult;
							//底下标注的点
							if ((daydata.year <= aVariable.calendar.year && daydata.month < aVariable
									.calendar.month) || (daydata.year == aVariable.calendar.year &&
									daydata.month == aVariable.calendar.month && daydata.day < aVariable
									.calendar.day)) {
								point.classList.remove("threehidden");
								point.classList.add("three");
							}
							//判断打卡状态
							if (attResult < 400) {
								result.style.color = "seagreen"
								if (attResult == 201) {
									result.style.color = "yellow"
								}
							} else if (attResult >= 400 && attResult <= 500) {
								result.style.color = "red"

							} else if (attResult > 500) {
								result.style.color = "orange"
							}

						} else {
							dayholi.classList.remove("zerohidden");
							dayholi.classList.add("zeroshow");
						}
					}
				} else {
					util.ToastTitle(data.msg);
				}
			} else {
				util.ToastTitle(data.msg);
			}
		}, function(error) {
			if (error != null) {
				if (JSON.stringify(error).length < 5) {
				util.ToastTitle("请求日历信息失败");
					return;
				}
				util.ToastTitle(JSON.parse(error).msg);
			} else {
				util.ToastTitle("请求日历信息失败");
			}
		});
	},

	loadToday: function() {
		var now_date = new Date();
		var nowYear = now_date.getFullYear();
		var nowMonth = now_date.getMonth() + 1;
		var nowDay = now_date.getDate();

		aVariable.calendar.year = nowYear;
		aVariable.calendar.month = nowMonth;
		aVariable.calendar.day = nowDay;
		aFunc.dateTopView(nowYear, nowMonth, nowDay, "今日");
		aVariable.view.calendarText.innerHTML = nowDay;

		var dateStr = nowYear + "-" + nowMonth + "-" + nowDay;
		aVariable.data.lastDateStr = dateStr;

		aFunc.creatCalendar(parseInt(nowYear), parseInt(nowMonth) - 1);
		aFunc.getCalendarData(dateStr);
	},

	dateTopView: function(year, month, date, lunar) {
		aVariable.view.todayDate.innerHTML = month + "月" + date + "日";
		aVariable.view.year.innerHTML = year;
		aVariable.view.lunar.innerHTML = lunar;
	},


	bindEvent: function() {
		aVariable.view.todayContent.addEventListener("tap", function() {

			var year = aVariable.calendar.year;
			var month = aVariable.calendar.month - 1;
			var day = aVariable.calendar.day;
			mui.openWindow({
				id: 'year-calendar',
				url: '../year-calendar/year-calendar.html',
				extras: {
					year: year,
					month: month,
					day: day,
				},
				styles: {
					popGesture: "none"
				},
				show: {
					aniShow: 'fade-in'
				},
				waiting: {
					autoShow: false
				}
			});

		});

		aVariable.view.signBtnOn.addEventListener("tap", function() {
			aFunc.enterHandleException(aVariable.data.onSignId, aVariable.data.classId, aVariable.data
				.onRemarkId);
		});

		aVariable.view.signBtnOff.addEventListener("tap", function() {
			aFunc.enterHandleException(aVariable.data.offSignId, aVariable.data.classId, aVariable.data
				.offRemarkId);
		});

		//返回今天日期
		aVariable.view.todayIcon.addEventListener("tap", function() {
			var nowDay = aVariable.calendar.day;
			var nowMonth = aVariable.calendar.month;
			var nowYear = aVariable.calendar.year;

			var oldDates = aVariable.data.lastDateStr.split('-');

			var dateStr = nowYear + "-" + nowMonth + "-" + nowDay;
			aVariable.data.lastDateStr = dateStr;
			//更新日历
			//当月重构日历
			if (oldDates.length >= 2) {
				if (!(nowYear == oldDates[0] && nowMonth == oldDates[1])) {
					aFunc.creatCalendar(parseInt(nowYear), parseInt(nowMonth) - 1);
				}
			}
			//显示顶部相关信息农历
			var lunarData = lunarTool.sloarToLunar(nowYear, nowMonth, nowDay)
			var lunarDay = lunarData.lunarDay;

			aFunc.dateTopView(nowYear, nowMonth, nowDay, lunarDay);
			//当前异常情况说明
			aFunc.requestUserDaySign(dateStr);
			aFunc.getCalendarData(dateStr);
			//选择状态
			aFunc.selectItem(nowYear, nowMonth, nowDay);
		});
		//点击选择的日期
		mui('.mui-table-view').on("tap", 'li', function() {
			var card = this;
			var year = card.getAttribute("data-year");
			var month = card.getAttribute("data-month");
			var day = card.getAttribute("data-day");
			if (day.length == 0) {
				return;
			}
			if (day <= 0) {
				return;
			}
			//请求当前的用户打卡信息
			var dateStr = year + "-" + month + "-" + day;
			aVariable.data.lastDateStr = dateStr;
			aFunc.requestUserDaySign(dateStr);
			//显示顶部相关信息农历
			var lunarData = lunarTool.sloarToLunar(year, month, day)
			var lunarDay = lunarData.lunarDay;
			aFunc.dateTopView(year, month, day, lunarDay);
			//更改选中的颜色
			aFunc.selectItem(year, month, day);
		});

	},


	enterHandleException: function(signId, classId, remarkId) {
		mui.openWindow({
			id: 'handle-exception',
			url: '../handle-exception/handle-exception.html',
			extras: {
				signId: signId,
				classId: classId,
				remarkId: remarkId,
			},
			styles: {
				popGesture: "none"
			},
			show: {
				aniShow: 'slide-in-right'
			},
			waiting: {
				autoShow: false
			}
		});
	},

	// 请求用户打卡信息
	requestUserDaySign: function(dateStr, noshow) {
		var wt = "";
		if (noshow != "noshow") {
			wt = plus.nativeUI.showWaiting("加载中...");
		}
		attendServer.userSignDetails(dateStr, function(data) {
			if (noshow != "noshow") {
				wt.close();
			}
			if (data.code == "200") {
				if (data.data.length > 0) {
					aFunc.updateUserSignView(data.data[data.data.length - 1]);
				} else {
					util.ToastTitle("未找到此日的打卡信息");
					aVariable.view.shiftInfo.style.display = "none";
				}
			} else {
				aVariable.view.shiftInfo.style.display = "none";
				util.ToastTitle(data.msg);
			}
		}, function(error) {
			if (noshow != "noshow") {
				wt.close();
			}
			aVariable.view.shiftInfo.style.display = "none";
			if (error != null) {
				if (JSON.stringify(error).length < 5) {
					util.ToastTitle("请求用户打卡信息失败");
					return;
				}
				util.ToastTitle(JSON.parse(error).msg);
			} else {
				util.ToastTitle("请求用户打卡信息失败");
			}
		});
	},

	updateUserSignView: function(data) {
		aVariable.data.classId = data.classId;
		aVariable.data.onSignId = data.onSignId;
		aVariable.data.onRemarkId = data.onRemarkId;
		aVariable.data.offSignId = data.offSignId;
		aVariable.data.offRemarkId = data.offRemarkId;

		//显示打卡信息
		aVariable.view.shiftInfo.style.display = "";
		//班次
		aVariable.view.shiftTitle.innerHTML = data.className + "（" + data.signDate + "）";
		//上班
		aVariable.view.signStateOn.innerHTML = data.signOnResultName + " " + data.signOnTime;
		aVariable.view.feedbackTitleOn.innerHTML = data.onRemarkTypeName;
		aVariable.view.feedbackContentOn.innerHTML = data.onRemark;
		aVariable.view.positionAdressOn.innerHTML = data.signOnAddress;
		if (data.onRemarkTypeName != null && data.onRemarkTypeName.length > 0) {
			aVariable.view.signBtnOn.innerHTML = "更新说明";
		} else {
			aVariable.view.signBtnOn.innerHTML = "处理异常";
		}

		//下班
		aVariable.view.signStateOff.innerHTML = data.signOffResultName + " " + data.signOffTime;
		aVariable.view.feedbackTitleOff.innerHTML = data.offRemarkTypeName;
		aVariable.view.feedbackContentOff.innerHTML = data.offRemark;
		aVariable.view.positionAdressOff.innerHTML = data.signOffAddress;
		if (data.offRemarkTypeName != null && data.offRemarkTypeName.length > 0) {
			aVariable.view.signBtnOff.innerHTML = "更新说明";
		} else {
			aVariable.view.signBtnOff.innerHTML = "处理异常";
		}


	},


	//以下创建日历
	creatCalendar: function(year, month) {

		var holder = document.getElementById("days");
		var now_year = aVariable.calendar.year;
		var now_month = aVariable.calendar.month - 1;
		var now_day = aVariable.calendar.day;

		var str = "";
		var totalDay = aFunc.daysMonth(month, year); //获取该月总天数
		var firstDay = aFunc.dayStart(month, year); //获取该月第一天是星期几
		var endDay = aFunc.dayEnd(month, year);
		var myclass;

		var lastMonthNum = month - 1;
		var lastMonth = null;
		if (firstDay <= 6) {
			for (var i = (firstDay - 1); i >= 0; i--) {
				if (lastMonthNum >= 0) {
					lastMonth = aFunc.daysMonth(lastMonthNum, year);
				} else {
					lastMonth = aFunc.daysMonth(11, year - 1);
				}
				lastMonth -= i;
				//为起始日之前的日期创建空白节点				
				str += aFunc.calendarHtml(year, month, lastMonth, myclass)
			}
		}
		//本月
		for (var i = 1; i <= totalDay; i++) {
			if (i < now_day) {
				myclass = "darkgrey"; //当该日期在今天之前时，以浅灰色字体显示
			} else if (i == now_day && year == now_year && month == now_month) {
				myclass = "today-color"; //当天日期以绿色背景突出显示
			} else {
				myclass = "darkgrey"; //当该日期在今天之后时，以深灰字体显示
			}
			str += aFunc.calendarCurHtml(year, month, i, myclass);
		}


		if (endDay <= 6) {
			for (var i = 1; i < (6 - endDay + 1); i++) {
				//为起始日之前的日期创建空白节点
				str += aFunc.calendarHtml(year, (month + 1), i, "")

			}
		} else if (endDay == 7) {
			for (var i = 1; i < 7; i++) {
				//为起始日之前的日期创建空白节点
				str += aFunc.calendarHtml(year, (month + 1), i, "")
			}
		}
		holder.innerHTML = str; //设置日期显示
	},

	//获取某年某月第一天是星期几
	dayStart: function(month, year) {
		var tmpDate = new Date(year, month, 1);
		return (tmpDate.getDay());
	},
	//获取某年某月最后一天是星期几
	dayEnd: function(month, year) {
		var monthNum = aFunc.daysMonth(month, year);
		var tmpDate = new Date(year, month, monthNum);
		return (tmpDate.getDay());
	},

	//获取该月总天数,计算某年是不是闰年，通过求年份除以4的余数即可 
	daysMonth: function(month, year) {
		year = parseInt(year);
		if ((year % 4 == 0 && year % 100 !== 0) || year % 400 == 0) {
			return (aVariable.calendar.month_olympic[month]);
		} else {
			return (aVariable.calendar.month_normal[month]);
		}
	},

	calendarHtml: function(year, month, day, myclass) {
		var str = '<li  data-year="' + year + '" data-month="' + (month + 1) +
			'" data-day="-1"' + 'class= "daysli lightgrey' + '"' + '>' +
			'<div class="zerohidden">' + "假" + '</div>' +
			'<div  class="calendar-item ' + myclass + '">' +
			'<div class="one lightgrey">' + day + '</div>' +
			'<div style="display:" class="two" name="two">' + "&nbsp" + '</div>' +
			'<div style="display:" class="point threehidden">' + "  " + '</div>' +
			'</div>' +
			'</li>';
		return str;
	},


	calendarCurHtml: function(year, month, day, myclass) {
		var str = '<li   data-year="' + year + '" data-month="' + (month + 1) +
			'" data-day="' + day + '"' + 'class= "daysli ' + '"' + '>' +
			'<div id = holi' + day + ' class="zerohidden">' + "假" + '</div>' +
			'<div id =days' + day + ' class="calendar-item ' + myclass + '">' +
			'<div class="one">' + day + '</div>' +
			'<div style="display:" class="two">' + "&nbsp" + '</div>' +
			'<div style="display:" class="point threehidden">' + " " + '</div>' +
			'</div>' +
			'</li>';
		return str;
	},


	selectItem: function(year, month, day) {
		if (aVariable.calendar.oldItem != null) {
			var oldliID = "days" + aVariable.calendar.oldItem;
			var oldli = document.getElementById(oldliID);
			oldli.classList.remove('select-color');
			oldli.style.backgroundColor = "";
			oldli.style.color = "#565656";
			if ((year <= aVariable.calendar.year && month < aVariable.calendar.month) || (year == aVariable
					.calendar.year && month == aVariable.calendar.month && aVariable.calendar.oldItem <
					aVariable.calendar.day)) {
				var oldHoliID = "holi" + aVariable.calendar.oldItem;
				var oldholi = document.getElementById(oldHoliID);
				if (oldholi.className.indexOf("zeroshow") < 0) {
					var oldPoint = oldli.getElementsByClassName("point")[0];
					oldPoint.style.background = "rgba(136, 136, 136, 1)";
				}
			}
		}
		var liID = "days" + day;
		var newli = document.getElementById(liID);
		newli.style.backgroundColor = "rgba(0, 104, 237, 1)";
		newli.style.color = "#FFFFFF";
		aVariable.calendar.oldItem = day;
		if (day != aVariable.calendar.day && year == aVariable.calendar.year && month == aVariable.calendar
			.month) {
			var today = "days" + aVariable.calendar.day;
			var dayli = document.getElementById(today);
			dayli.style.backgroundColor = "rgba(234, 234, 234, 1)";
			dayli.style.color = "#565656";
		}
		if ((year <= aVariable.calendar.year && month < aVariable.calendar.month) || (year == aVariable.calendar
				.year && month == aVariable.calendar.month && day < aVariable.calendar.day)) {
			var todayholiID = "holi" + day;
			var dayholi = document.getElementById(todayholiID);
			if (dayholi.className.indexOf("zeroshow") < 0) {
				var point = newli.getElementsByClassName("point")[0];
				point.style.background = "white"
			}
		}
	}
};
